const { join, resolve } = require('path');
const webpack = require('webpack');
const glob = require('glob');

const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CommonsChunkPlugin = require('webpack/lib/optimize/CommonsChunkPlugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');

let entries = {};
let chunks = [];
getEntriesAndChunks();

let config = {
    entry: entries,
    // devtool: 'cheap-module-source-map',
    output: {
        path: resolve(__dirname, '51jili/dist2'),
        filename: '[name].js',
        // filename: 'script/[id].js',
        publicPath: process.env.NODE_ENV === 'production' ? '../' : '/'
    },
    resolve: {
        //配置别名，在项目中可缩减引用路径
        extensions: ['.js', '.vue'],
        alias: {
            assets: join(__dirname, '/src/assets'),
            components: join(__dirname, '/src/components'),
            lib: join(__dirname, '/src/lib'),
            src: join(__dirname, '/src'),
            root: join(__dirname, 'node_modules'),
            vue: 'vue/dist/vue.js',
            jquery:'jquery'
        }
    },
    externals: [
        // { apiready: "window.apiready" },
        { api: "window.api" }
        // { MYAPP: "window.APP" }
    ],
    module: {
        rules: [{
                test: /\.vue$/,
                loader: 'vue-loader',
                options: {
                  extractCSS: true,
                  loaders: {
                    scss: 'vue-style-loader!css-loader!sass-loader', // <style lang="scss">
                    sass: 'vue-style-loader!css-loader!sass-loader?indentedSyntax' // <style lang="sass">
                  }
                }
            },
            {
                test: /\.js$/,
                use: 'babel-loader',
                exclude: /node_modules/
            },
            {
                test: /\.css$/,
                use: ExtractTextPlugin.extract({
                    fallback: 'style-loader',
                    use: 'css-loader'
                })
            },
            {
              test: /\.scss$/,
              use: [{
                  loader: "style-loader" // compiles Sass to CSS
              },{
                  loader: "css-loader" // compiles Sass to CSS
              },{
                  loader: "sass-loader" // compiles Sass to CSS
              }]
          },
            {
                test: /\.html$/,
                // use: [ 'file-loader?name=[path][name].[ext]!extract-loader!html-loader' ]
                use: [{
                    loader: 'html-loader',
                    options: {
                        root: resolve(__dirname, 'src'),
                        attrs: ['img:src', 'link:href']
                    }
                }]
            },
            {
                test: /\.(png|jpe?g|gif|svgz)(\?.+)?$/,
                exclude: /iconfont\.svg/,
                use: [{
                    loader: 'url-loader',
                    options: {
                        limit: 10000,
                        name: 'assets/img/[name].[ext]'
                    }
                }]
            },
            // {
            //     test: /\.(eot|ttf|woff|woff2|svg|svgz)(\?.+)?$/,
            //     use: [{
            //         loader: 'file-loader',
            //         options: {
            //             name: 'assets/fonts/[name].[ext]'
            //         }
            //     }]
            // },
            {
                test: /\.(eot|ttf|woff|woff2|svg|svgz)(\?.+)?$/,
                include: /fonts/,
                use: [{
                    loader: 'url-loader',
                    options: {
                        limit: 10000,
                        name: 'assets/fonts/[name].[ext]'
                    }
                }]
            }
        ]
    },
    plugins: [
        new CleanWebpackPlugin(['51jili/dist2']),
        new CopyWebpackPlugin([
            { from: 'res', to: '../res' },
            { from: 'config.xml', to: '../config.xml' },
            { from: 'index.html', to: '../index.html' }
        ]),
        new CommonsChunkPlugin({
            name: 'common',
            filename: 'assets/js/common.js',
            chunks: getCommonChunks(chunks),
            minChunks: 2
        }),
        // new CommonsChunkPlugin({
        //     name: 'vendor',
        //     chunks: ['common'],
        //     filename: 'assets/js/vendor.bundle.js',
        //     minChunks: Infinity,
        // }),
        new ExtractTextPlugin({
            filename: 'css/[name].css',
            allChunks: true
        }),
        new webpack.ProvidePlugin({
          $:'jquery',
          jQuery:'jquery',
          'window.jQuery': 'jquery',
          'window.$': 'jquery',
        }),
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            },
            sourceMap: true
        })
    ],
    devServer: {
        host: '0.0.0.0',
        port: 8010,
        historyApiFallback: false,
        noInfo: true,
        proxy: {
            '/api': {
                // target: 'http://ksh.51jili.com',
                // target: 'https://www.51jili.com',
                // target:'http://192.168.20.4',
                // target:'http://test.51jili.com',
                target:'http://bugfix.51jili.com',
                changeOrigin: true,
                pathRewrite: { '^/api': '/api2' }
            }
        }
    },
    devtool: '#eval-source-map'
};

const pages = getHtmls();

pages.forEach(function(pathname) {
    // filename 用文件夹名字

    let fileBasename = pathname.substring(6, pathname.lastIndexOf('/'));
    var conf = {
        filename: fileBasename + '.html', //生成的html存放路径，相对于path
        template: 'src/' + pathname + '.html', //html模板路径
    };
    var chunk = pathname.substring(6, pathname.lastIndexOf('/'));
    if (chunks.indexOf(chunk) > -1) {
        conf.inject = 'body';
        conf.chunks = ['common', chunk];
    }
    if (process.env.NODE_ENV === 'production') {
        conf.hash = true;
    }
    config.plugins.push(new HtmlWebpackPlugin(conf));
});

function getCommonChunks(chunks) {
    let newChunks = [];
    chunks.forEach(function(item) {
        if (!item.includes('questions')) {
            newChunks.push(item);
        }
    });
    // console.log(newChunks);
    return newChunks;
}

module.exports = config;

function getEntriesAndChunks() {
    glob.sync('./src/pages/**/*.js').forEach(function(name) {
        var n = name.slice(name.lastIndexOf('src/') + 10, name.lastIndexOf('/'));
        // var n = name.slice(name.lastIndexOf('src/') + 10, name.length - 3);
        entries[n] = [name];
        chunks.push(n);
    });
    // entries['vendor'] = ['vue'];

}

function getHtmls() {
    var htmls = [];
    glob.sync('./src/pages/**/*.html').forEach(function(name) {
        var n = name.slice(name.lastIndexOf('src/') + 4, name.length - 5);
        htmls.push(n);
    });
    return htmls;
}

if (process.env.NODE_ENV === 'production') {
    module.exports.devtool = '#source-map';
    // http://vue-loader.vuejs.org/en/workflow/production.html
    module.exports.plugins = (module.exports.plugins || []).concat([
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: '"production"'
            }
        }),
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            }
        })
    ]);
}
